import { KeywordModel} from '../../models/keyword.js'
import { BookModel } from '../../models/book.js'
import { paginationBev } from '../behaviors/pagination.js'
const keywordModel = new KeywordModel()
const bookModel = new BookModel()
Component({
  behaviors: [paginationBev],
  // 属性定义（详情参见下文）
  properties: {
    more:{
      type:String,
      observer:'loadMore'
    }
  },
  data: {
    historyWords:[],
    hotWords:[],
    searching:false,
    q:'',
    loading:false,
    loadingCenter:false
  }, // 私有数据，可用于模板渲染
  lifetimes: {
    // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
    attached() {
      //const historyWords=keywordModel.getHistory()
      //const hotWords = keywordModel.getHot()
      this.setData({
        historyWords: keywordModel.getHistory()
      })
      keywordModel.getHot().then(res=>{
        this.setData({
          hotWords: res.hot
        })
      })
    },
    moved() { },
    detached() { },
  },
  // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
  attached() { }, // 此处attached的声明会被lifetimes字段中的声明覆盖
  ready() { },
  pageLifetimes: {
    // 组件所在页面的生命周期函数
    show() { },
    hide() { },
    resize() { },
  },
  methods: {
    onCancel(){
      this.triggerEvent('cancel',{
      })
      this.initialize()
    },
    onConfirm(e){
      console.log(e)
      const q = e.detail.value || e.detail.text
      if(q){
        this._showLoadingCenter()
        this.setData({
          searching: true
        })
        bookModel.search(0, q).then(res => {
          this.setMoreData(res.books)
          this.setTotal(res.total)
          this.setData({
            q:q
          })
          keywordModel.addToHistory(q)
          this._hideLoadingCenter()
        })
      }else{
        wx.showToast({
          title: '请输入搜索关键词',
          icon:'none'
        })
      }
    },
    onDelete(e){
      this.setData({
        searching: false,
        q:''
      })
      this.initialize()
    },
    loadMore(e){
      console.log(e)
      if(!this.data.q){
        return
      }
      if(this.data.loading){
        return
      }
      //const length=this.data.dataArray.length
      if(this.hasMore()){
        this.setData({
          loading:true
        })
        bookModel.search(this.getCurrentStart(),this.data.q).then(res=>{
          this.setMoreData(res.books)
          this.setData({
            loading: false
          })
        },err=>{
          this.setData({
            loading: false
          })
        })
      }
    },
    _showLoadingCenter(){
      this.setData({
        loadingCenter:true
      })
    },
    _hideLoadingCenter() {
      this.setData({
        loadingCenter: false
      })
    }
  }
})
